
package edu.weber.bookstore.util;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 
 * 
 */
public class DatabaseModel
{
	private int _id = 0;
	
	/**
	 * Constructor for the DatabaseModel class.
	 * @param id primary key for a database table.
	 */
	protected DatabaseModel(int id)
	{
		_id = id;
	}
	
	/**
	 * 
	 * @return The database table name associated with this class
	 */
	protected String getTableName()
	{
		return "database_models";
	}
	
	/**
	 * Creates an object in the database. Must be overridden in a custom DatabaseModel.
	 * @throws SQLException 
	 */
	protected void create() throws SQLException
	{
		throw new SQLException("No database table tied to this model.");
	}
	
	/**
	 * Updates a specific object in the database. Must be overridden in a custom DatabaseModel.
	 * @throws SQLException 
	 */
	protected void update() throws SQLException
	{
		throw new SQLException("No database table tied to this model.");
	}
	
	/**
	 * DatabaseModel save function. If the ID for the model is 0 we call create. Otherwise update.
	 * @throws SQLException 
	 */
	public void save() throws SQLException
	{
		if(getId() == 0)
		{
			create();
		}
		else
		{
			update();
		}
	}

	/**
	 * Generic delete for the database model. Only deletes the one instance where the ID = _id;
	 * @throws SQLException 
	 */
	public void delete() throws SQLException
	{
		if(getId() != 0)
		{
			PreparedStatement pm = DatabaseConnection.getConnection().prepareStatement("DELETE FROM ".concat(getTableName()).concat(" WHERE id = ? LIMIT 1;"));
			pm.setInt(1, getId());
			if(pm.execute())
			{
				setId(0);
			}
		}
	}
	
	/**
	 * Getter for the primary key
	 * @return the primary key for the DatabaseModel
	 */
	public int getId()
	{
		return _id;
	}
	
	/**
	 * Sets the DatabaseModel's primary key.
	 * @param id the primary key for our DatabaseModel.
	 */
	public void setId(int id)
	{
		_id = id;
	}
}
